<?php

namespace backend\controllers;

use Yii;
use common\models\UserInfo;
use backend\models\UserInfoSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\UserMessage;
use backend\models\SysPermission;
use common\models\SmsLogRecord;
use liangzoe\mobilesmser\TextSmser;

/**
 * UserInfoController implements the CRUD actions for UserInfo model.
 */
class UserInfoController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all UserInfo models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new UserInfoSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        
        $model_permission = SysPermission::find()->all();

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        	'model_permission'=>$model_permission,
        ]);
    }
/**
 * 系统信息发送会员选择
 * @param unknown $msgid
 * @return Ambigous <string, string>
 */
    public function actionUserInfoForMessage($msgid,$msgtitle)
    {
    	$this->layout = 'main_small';
    	$searchModel = new UserInfoSearch();
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    
    	return $this->render('user_info_for_message', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    			]);
    }
    /*选择系统消息发送用户*/
    public function actionSelectMessageUser($msgid,$users_id)
    {
    //	$model_have = UserMessage::findAll($condition)
    	if(!empty($msgid) && !empty($users_id)){
    		$_arr = explode(',',$users_id);
    		foreach ($_arr as $value)
    		{   if(UserMessage::findOne(['msgid'=>$msgid,'uid'=>$value]) != null) continue;
    			$model = New UserMessage();
    			$model->uid = $value;
    			$model->msgid = $msgid;
    			$model->read = 0;
    			$model->save();
    		}
    	}

    }
    
    /*选择用户发送短信*/
    public function actionSendSmsUser($msg,$users_id)
    {
    	
    	if(!empty($msg) && !empty($users_id)){
    		$_arr = explode(',',$users_id);//发送的用户
    		$msg = $msg.' 退订回复TD';
    		foreach ($_arr as $value)
    		{   
    			$user = UserInfo::getUsernameById($value);
    			$smser = new TextSmser();
    			$smser->sendSMSbatch($user['tel'], $msg);
    			
	    		$model = New SmsLogRecord();
	    		$model->send_uid = Yii::$app->user->identity->id;
	    		$model->accept_uid = $value;
	    		$model->send_content = $msg;
	    		$model->send_time = time();
	    		$model->save();
	    		
    		}
    	}
    	echo '短信已发送';
    }
    
    /*批量设置用户权限*/
    public function actionSetBatchPermissionUser($permission,$users_id)
    {
    	
    	if(!empty($permission) && !empty($users_id)){
    		$permission = substr($permission, 1);
    		$_arr = explode(',',$users_id);//发送的用户
    		foreach ($_arr as $value)
    		{
    			$user = UserInfo::findOne(['id'=>$value]);
				$user->permission = $permission;
				$user->save();	   
    		}
    	}
    	echo '批量设置权限已成功';
    }
    /**
     * Displays a single UserInfo model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new UserInfo model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new UserInfo();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing UserInfo model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing UserInfo model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }
/**
 * 设置前端用户的权限
 * @param unknown $id
 * @return Ambigous <string, string>
 */
    public function actionUserPermission($id)
    {
    	$model = $this->findModel($id);
    	$model_permission = SysPermission::find()->all();
    	$model->permission = explode(',', $model->permission);//转为数组，在checkboxlist可被选中
    	
    	if ($model->load(Yii::$app->request->post())) {
    		$model->permission = !empty($model->permission)?implode(',', $model->permission):0;
    		
    		if($model->save()){
    			session_start();
    		//	Yii::$app->session->setFlash('danger','更新成功');
    			Yii::$app->getSession()->setFlash('success', "<div style='width:30%;border:1px solid #DFF0D8;background-color:#D6E9C6;padding:20px;'>更新成功</div>");
    			$model->permission = explode(',', $model->permission);
    			return $this->render('user_permission', [
    					'model' => $model,
    					'model_permission' => $model_permission
    					]);
    		}
    		else{
    			Yii::$app->getSession()->setFlash('success', "<div style='width:30%;border:1px solid #DFF0D8;background-color:#D6E9C6;padding:20px;'>更新失败</div>");
    			 
    		}
    		//return $this->redirect(['view', 'id' => $model->id]);
    	} else {
    		return $this->render('user_permission', [
    				'model' => $model,
    				'model_permission' => $model_permission
    				]);
    	}
    }
    
    public function get_ext($model,$field)
    {
    	$arr = array();
    	foreach ($model as $value){
    		array_push($arr, $value[$field]);
    	}
    	return $arr;
    }
    /*设置所有用户的权限*/
    public function actionSetAllUserPermission($users){
    	$this->layout = 'small_main';
    	$model = UserInfo::find()->all();
    	$model_permission = SysPermission::find()->all();
    	$model->permission = explode(',', $model->permission);//转为数组，在checkboxlist可被选中
    	 
    	if ($model->load(Yii::$app->request->post())) {
    		$model->permission = !empty($model->permission)?implode(',', $model->permission):0;
    	
    		if($model->save()){
    			session_start();
    			//	Yii::$app->session->setFlash('danger','更新成功');
    			Yii::$app->getSession()->setFlash('success', "<div style='width:30%;border:1px solid #DFF0D8;background-color:#D6E9C6;padding:20px;'>更新成功</div>");
    			$model->permission = explode(',', $model->permission);
    			return $this->render('user_permission', [
    					'model' => $model,
    					'model_permission' => $model_permission
    					]);
    		}
    		else{
    			Yii::$app->getSession()->setFlash('success', "<div style='width:30%;border:1px solid #DFF0D8;background-color:#D6E9C6;padding:20px;'>更新失败</div>");
    	
    		}
    		//return $this->redirect(['view', 'id' => $model->id]);
    	} else {
    		return $this->render('set_all_user_permission', [
    				'model' => $model,
    				'model_permission' => $model_permission
    				]);
    	}
    }
    public function actionSetPermissionAllUser($msgid,$users_id)
    {
    	//	$model_have = UserMessage::findAll($condition)
    	if(!empty($msgid) && !empty($users_id)){
    		$_arr = explode(',',$users_id);
    		foreach ($_arr as $value)
    		{   if(UserMessage::findOne(['msgid'=>$msgid,'uid'=>$value]) != null) continue;
    		$model = New UserMessage();
    		$model->uid = $value;
    		$model->msgid = $msgid;
    		$model->read = 0;
    		$model->save();
    		}
    	}
    
    }
    /**
     * Finds the UserInfo model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return UserInfo the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = UserInfo::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}
